package com.heima.media.task;

import com.heima.media.service.IAuditService;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RBoundedBlockingQueue;
import org.redisson.api.RDelayedQueue;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @author: itheima
 * @create: 2022-01-18 12:39
 */
@Service
@Async
@Slf4j
public class MediaTask {

    @Autowired
    private RedissonClient redissonClient;

    @Autowired
    private IAuditService auditService;


    /**
     * 异步任务：监听到延迟发布文章进行发布
     */
    public void handlerMsg() {
        try {
            //1.创建阻塞队列
            RBoundedBlockingQueue<Object> blockingQueue = redissonClient.getBoundedBlockingQueue("article-publish");

            //2.创建延迟队列
            RDelayedQueue<Object> delayedQueue = redissonClient.getDelayedQueue(blockingQueue);

            //3.发送测试消息
            delayedQueue.offer("init", 1, TimeUnit.SECONDS);
            while (true) {
                //监听消息，如果没有监听到消息，会进入到30阻塞状态
                String result = (String) blockingQueue.poll(30, TimeUnit.SECONDS);
                if (result != null && !result.equals("init")) {
                    System.out.println("接收到了消息：" + result);
                    int articleId = Integer.parseInt(result);
                    auditService.audit(articleId);
                }
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
            log.info("监听延迟消息异常p:{}", e.getMessage());
        }
    }
}
